package link.tengfei.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import link.tengfei.util.CreateCodeImage;
import link.tengfei.util.CreateRandomCharacter;
import sun.misc.BASE64Encoder;

/**
 * Servlet implementation class DrawImgServlet
 */
@WebServlet("/drawimg")
public class DrawImgServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static String randomnum = null;

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String vericode = CreateRandomCharacter.getSecurityCode();
		HttpSession session = request.getSession();
		session.setAttribute("verityCode", vericode);
		// 设置返回的内容
		response.setContentType("image/jpeg");
		// 浏览器不缓存响应内容--验证码图片，点一次就要刷新一次，所以不能有缓存出现
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		// 设置验证码失效时间
		response.setDateHeader("Expires", 0);
		// 以字节流发过去，交给img的src属性去解析即可
		ByteArrayOutputStream baos = new ByteArrayOutputStream();// io流
		ImageIO.write(new CreateCodeImage(vericode).createImage(), "png", baos);
		// 将图片转换成base64编码
		byte[] bytes = baos.toByteArray();// 转换成字节
		BASE64Encoder encoder = new BASE64Encoder();
		String png_base64 = encoder.encodeBuffer(bytes);// 转换成base64串
		png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");// 删除 \r\n
		response.getWriter().write(png_base64);

		randomnum = vericode;
	}

	public static String randomNum() {
		return randomnum;
	}

}
